import 'dart:developer';
import 'dart:math' as math;

import 'package:flutter/material.dart';
import 'package:flutter_demo/page/a_start/scaffold_page.dart';
import 'common_page.dart';
import 'next_page.dart';
import 'widget/test_animated_list.dart';
import 'widget/test_page_view.dart';
import 'package:flutter_public/flutter_public.dart';

/// FileName start_page
///
/// @Author lax
/// @Date 2024/6/4
///
/// @Description

class StartPage extends StatefulWidget {
  const StartPage({super.key});

  @override
  State<StatefulWidget> createState() {
    return _StartPageState();
  }
}

class _StartPageState extends State<StartPage> {
  bool _switchSelected = true; //维护单选开关状态
  bool? _checkboxSelected = true; //维护复选框状态

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      child: Scaffold(
        appBar: AppBar(
          title: const Text('Flutter入门'),
          centerTitle: true,
          backgroundColor: Colors.lightGreen,
        ),
        body: body(),
      ),
      onTap: () {
        FocusScope.of(context).requestFocus(FocusNode());
      },
    );
  }

  Widget body() {
    return ListView(
      padding: const EdgeInsets.symmetric(horizontal: 16),
      physics: const AlwaysScrollableScrollPhysics(),
      children: [
        const Padding(
          padding: EdgeInsets.symmetric(vertical: 16),
          child: Text(
            '基础组件',
            style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
          ),
        ),
        baseWidget(),
        const Padding(
          padding: EdgeInsets.symmetric(vertical: 16),
          child: Text(
            '容器组件',
            style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
          ),
        ),
        containerWidget(),
        const Padding(
          padding: EdgeInsets.symmetric(vertical: 16),
          child: Text(
            '布局组件',
            style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
          ),
        ),
        constrainedWidget(),
        const Padding(
          padding: EdgeInsets.symmetric(vertical: 16),
          child: Text(
            '页面导航',
            style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
          ),
        ),
        navigationWidget(),
        const Padding(
          padding: EdgeInsets.symmetric(vertical: 16),
          child: Text(
            '页面骨架',
            style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
          ),
        ),
        scaffoldWidget(),
        const Padding(
          padding: EdgeInsets.symmetric(vertical: 16),
          child: Text(
            '滚动组件',
            style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
          ),
        ),
        scrollWidget(),
      ],
    );
  }

  /// 基础组件
  Widget baseWidget() {
    return SeparatedColumn(
      padding: const EdgeInsets.only(left: 16),
      separator: const SizedBox(height: 12),
      children: [
        const Text('文本'),
        Container(
          decoration: const BoxDecoration(
            color: Colors.grey,
            borderRadius: BorderRadius.all(Radius.circular(5)),
          ),
          child: TextButton(
            onPressed: () {
              log('点击按钮');
            },
            child: const Text('按钮'),
          ),
        ),
        ElevatedButton.icon(
          icon: const Icon(Icons.send),
          label: const Text("按钮"),
          onPressed: () {
            log('点击按钮');
          },
        ),
        const Row(
          children: [
            Text('图片'),
            Image(
              image: NetworkImage(
                  "https://avatars2.githubusercontent.com/u/20411648?s=460&v=4"),
              width: 100,
              height: 100,
            ),
          ],
        ),
        Row(
          children: [
            const Text('开关'),
            Switch(
              value: _switchSelected, //当前状态
              onChanged: (value) {
                //重新构建页面
                setState(() {
                  _switchSelected = value;
                });
              },
            ),
          ],
        ),
        Row(
          children: [
            const Text('复选框'),
            Checkbox(
              value: _checkboxSelected,
              activeColor: Colors.red, //选中时的颜色
              onChanged: (value) {
                setState(() {
                  _checkboxSelected = value;
                });
              },
            ),
          ],
        ),
        Container(
          decoration: BoxDecoration(
            borderRadius: const BorderRadius.all(Radius.circular(8)),
            border: Border.all(width: 1),
          ),
          child: TextField(
            decoration: const InputDecoration(
              labelText: "输入框",
              labelStyle: TextStyle(color: Colors.grey),
              hintText: "请输入用户名或邮箱",
              prefixIcon: Icon(Icons.person),
              border: InputBorder.none,
            ),
            onChanged: (value) {
              log(value);
            },
          ),
        ),
        Row(
          children: [
            const Padding(
              padding: EdgeInsets.all(16),
              child: Text('进度条'),
            ),
            // 圆形进度条直径指定为100
            SizedBox(
              height: 44,
              width: 44,
              child: CircularProgressIndicator(
                backgroundColor: Colors.grey[200],
                valueColor: const AlwaysStoppedAnimation(Colors.blue),
                value: .7,
              ),
            ),
          ],
        ),
        // 线性进度条高度指定为3
        SizedBox(
          height: 3,
          child: LinearProgressIndicator(
            backgroundColor: Colors.grey[200],
            valueColor: const AlwaysStoppedAnimation(Colors.blue),
            value: .5,
          ),
        ),
      ],
    );
  }

  /// 容器组件
  Widget containerWidget() {
    return SeparatedColumn(
      padding: const EdgeInsets.only(left: 16),
      separator: const SizedBox(height: 8),
      children: [
        const SizedBox(
          child: Text('SizedBox'),
        ),
        const Padding(
          padding: EdgeInsets.only(left: 22),
          child: Text('Padding'),
        ),
        Container(
          padding: const EdgeInsets.only(left: 44),
          child: const Text('Container'),
        ),
        // 也可以用Container代替decoration
        DecoratedBox(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: [Colors.red, Colors.orange.shade200],
            ), //背景渐变
            borderRadius: BorderRadius.circular(3.0), //圆角
            boxShadow: const [
              BoxShadow(
                  color: Colors.black54,
                  offset: Offset(2.0, 2.0),
                  blurRadius: 4.0),
            ],
          ), //阴影
          child: const Padding(
            padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
            child: Text(
              "DecoratedBox/Container",
              style: TextStyle(color: Colors.white),
            ),
          ),
        ),
        Container(
          margin: const EdgeInsets.only(top: 32),
          color: Colors.grey,
          child: Transform(
            alignment: Alignment.topRight, //相对于坐标系原点的对齐方式
            transform: Matrix4.skewY(0.3), //沿Y轴倾斜0.3弧度
            child: Container(
              padding: const EdgeInsets.all(8.0),
              color: Colors.deepOrange,
              child: const Text('Transform'),
            ),
          ),
        ),
        DecoratedBox(
          decoration: const BoxDecoration(color: Colors.red),
          //默认原点为左上角，左移20像素，向上平移5像素
          child: Transform.translate(
            offset: const Offset(24, -5),
            child: const Text("Transform平移"),
          ),
        ),
        DecoratedBox(
          decoration: const BoxDecoration(color: Colors.red),
          child: Transform.scale(
            scale: 1.5, //放大到1.5倍
            child: const Text("缩放"),
          ),
        ),
        DecoratedBox(
          decoration: const BoxDecoration(color: Colors.yellow),
          child: Transform.rotate(
            //Transform的变换是应用在绘制阶段 占用空间的大小和在屏幕上的位置固定不变
            angle: math.pi / 2, //旋转90度
            child: const Text("旋转"),
          ),
        ),
        const DecoratedBox(
          decoration: BoxDecoration(color: Colors.yellow),
          child: RotatedBox(
            //RotatedBox的变换是在layout阶段，会影响在子组件的位置和大小
            quarterTurns: 1, //旋转90度(1/4圈)
            child: Text("RotatedBox旋转"),
          ),
        ),
        const ClipOval(
          child: DecoratedBox(
            decoration: BoxDecoration(color: Colors.blue),
            child: Text("裁剪Clip"),
          ),
        ), //剪裁为圆形
        ClipRRect(
          borderRadius: BorderRadius.circular(5), //剪裁为圆角矩形
          child: const DecoratedBox(
            decoration: BoxDecoration(color: Colors.blue),
            child: Text("裁剪Clip"),
          ),
        ),
      ],
    );
  }

  /// 布局组件
  Widget constrainedWidget() {
    return SeparatedColumn(
      padding: const EdgeInsets.only(left: 16),
      separator: const SizedBox(height: 8),
      children: [
        ConstrainedBox(
          constraints: const BoxConstraints(
              minWidth: double.infinity, //宽度尽可能大
              minHeight: 50.0 //最小高度为50像素
              ),
          child: Container(
            height: 5.0,
            decoration: const BoxDecoration(color: Colors.blue),
            child: const Text('ConstrainedBox'),
          ),
        ),
        const SizedBox(
          child: Text('SizedBox'),
        ),
        Container(
          color: Colors.blue,
          child: const Text('Container'),
        ),
        Row(
          children: [
            const Text('横向线性布局Row: '),
            Expanded(
              child: Container(
                color: Colors.blue,
                child: const Text('剩余区域Expanded'),
              ),
            ),
          ],
        ),
        const Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Chip(label: Text('Between')),
            Chip(label: Text('Between')),
            Chip(label: Text('Between')),
          ],
        ),
        const Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            Chip(label: Text('Around')),
            Chip(label: Text('Around')),
            Chip(label: Text('Around')),
          ],
        ),
        const Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            Chip(label: Text('Evenly')),
            Chip(label: Text('Evenly')),
            Chip(label: Text('Evenly')),
          ],
        ),
        const Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('纵向线性布局Column: '),
            Text('Text1'),
            Text('Text2'),
          ],
        ),
        //Row和Column都继承自Flex，参数基本相同，所以能使用Flex的地方基本上都可以使用Row或Column
        Flex(
          direction: Axis.horizontal,
          children: [
            Expanded(
              flex: 1,
              child: Container(
                color: Colors.red,
                child: const Text('弹性布局Flex'),
              ),
            ),
            Expanded(
              flex: 2,
              child: Container(
                color: Colors.green,
                child: const Text('比例1:2'),
              ),
            ),
          ],
        ),
        const Wrap(
          spacing: 8.0, // 主轴(水平)方向间距
          runSpacing: 4.0, // 纵轴（垂直）方向间距
          alignment: WrapAlignment.start, //沿主轴方向居中
          children: <Widget>[
            Chip(
              padding: EdgeInsets.zero,
              label: Text('流式布局Wrap'),
            ),
            Chip(
              label: Text('流式布局Wrap'),
            ),
            Chip(
              avatar: CircleAvatar(
                backgroundColor: Colors.blue,
                child: Text('M'),
              ),
              label: Text('流式布局Wrap'),
            ),
          ],
        ),
        Stack(
          alignment: Alignment.center,
          children: [
            Container(
              color: Colors.green,
              width: 100,
              height: 100,
            ),
            const Text('层叠布局'),
            const Positioned(
              left: 4,
              top: 4,
              child: Text('Stack'),
            ),
          ],
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Container(
              height: 100,
              width: 100,
              color: Colors.blue.shade50,
              child: const Align(
                widthFactor: 2, //宽度为子组件宽度x2
                heightFactor: 2, //高度为子组件高度x2
                alignment: Alignment(2, -1), //x,y方向的偏移量 中心为原点
                child: FlutterLogo(size: 50),
              ),
            ),
            const Text('Alignment'),
            Container(
              color: Colors.blue[50],
              child: const Align(
                widthFactor: 2, //宽度为子组件宽度x2
                heightFactor: 2, //高度为子组件高度x2
                alignment: FractionalOffset(0.1, 0.5), //x,y方向的偏移量 左上角为原点
                child: FlutterLogo(
                  size: 50,
                ),
              ),
            ),
          ],
        ),
        const Row(
          children: [
            Chip(label: Text('空间适配FittedBox')),
            Chip(label: Text('空间适配FittedBox')),
            Chip(label: Text('空间适配FittedBox')),
          ],
        ),
        const FittedBox(
          child: Row(
            children: [
              Chip(label: Text('空间适配FittedBox')),
              Chip(label: Text('空间适配FittedBox')),
              Chip(label: Text('空间适配FittedBox')),
            ],
          ),
        ),
      ],
    );
  }

  /// 页面导航
  Widget navigationWidget() {
    return GestureDetector(
      onTap: () {
        Navigator.push(context, MaterialPageRoute(builder: (_) {
          return const NextPage(page: 1);
        }));
      },
      child: const Row(
        children: [
          Expanded(
            child: Text("Navigator"),
          ),
          Icon(Icons.chevron_right),
        ],
      ),
    );
  }

  /// 页面骨架
  Widget scaffoldWidget() {
    return Column(
      children: [
        GestureDetector(
          onTap: () {
            Navigator.push(context, MaterialPageRoute(builder: (_) {
              return const ScaffoldPage();
            }));
          },
          child: const Row(
            children: [
              Expanded(
                child: Text("Scaffold"),
              ),
              Icon(Icons.chevron_right),
            ],
          ),
        ),
        const SizedBox(height: 8),
        const DecoratedBox(
          decoration: BoxDecoration(color: Colors.black12),
          child: Text('''
Scaffold(
  // 导航栏
  appBar: AppBar(
    title: const Text("App Name"),
    actions: <Widget>[
      //导航栏右侧菜单
      IconButton(
          icon: const Icon(Icons.share),
          onPressed: () {
            log('分享');
          }),
    ],
  ),
  body: Center(
      child: TextButton(
    onPressed: () {
      Navigator.pop(context);
    },
    child: const Text("返回"),
  )),
  // 抽屉
  drawer: const Drawer(),
  // 底部导航栏
  bottomNavigationBar: BottomNavigationBar(
    items: const [
      BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'),
      BottomNavigationBarItem(
          icon: Icon(Icons.business), label: 'Business'),
      BottomNavigationBarItem(icon: Icon(Icons.school), label: 'School'),
    ],
    currentIndex: _bottomNavigationBarIndex,
    fixedColor: Colors.blue,
    onTap: (int index) {
      setState(() {
        _bottomNavigationBarIndex = index;
      });
    },
  ),
  // 悬浮按钮
  floatingActionButton: FloatingActionButton(
      child: const Icon(Icons.add),
      onPressed: () {
        log('添加');
      }),
)'''),
        ),
      ],
    );
  }

  /// 滚动组件
  Widget scrollWidget() {
    return SeparatedColumn(
      padding: const EdgeInsets.only(bottom: 44),
      separator: const Divider(thickness: 1, height: 1),
      children: [
        GestureDetector(
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (_) {
                final data = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split("");
                return CommonPage(
                  title: 'SingleChildScrollView',
                  body: Scrollbar(
                    child: SingleChildScrollView(
                      padding: const EdgeInsets.all(16.0),
                      child: Center(
                        child: Column(
                          children: data
                              .map((c) => Text(c, textScaleFactor: 2))
                              .toList(),
                        ),
                      ),
                    ),
                  ),
                );
              }),
            );
          },
          child: const ListTile(
            title: Text('SingleChildScrollView'),
          ),
        ),
        GestureDetector(
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (_) {
                final data = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split("");
                return CommonPage(
                  title: 'ListView',
                  body: ListView(
                    padding: const EdgeInsets.all(16.0),
                    children:
                        data.map((c) => Text(c, textScaleFactor: 2)).toList(),
                  ),
                );
              }),
            );
          },
          child: const ListTile(
            title: Text('ListView'),
          ),
        ),
        GestureDetector(
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (_) {
                final data = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split("");
                return CommonPage(
                  title: 'ListView.separated',
                  body: ListView.separated(
                    padding: const EdgeInsets.all(0),
                    separatorBuilder: (context, index) {
                      return const Divider(thickness: 1, height: 1);
                    },
                    itemCount: data.length,
                    itemBuilder: (context, index) {
                      return ListTile(
                        title: Text(data[index], textScaleFactor: 2),
                      );
                    },
                  ),
                );
              }),
            );
          },
          child: const ListTile(
            title: Text('ListView.separated'),
          ),
        ),
        GestureDetector(
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (_) {
                return const CommonPage(
                  title: 'AnimatedList',
                  body: TestAnimatedList(),
                );
              }),
            );
          },
          child: const ListTile(
            title: Text('AnimatedList'),
          ),
        ),
        GestureDetector(
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (_) {
                return CommonPage(
                  title: 'GridView',
                  body: GridView(
                    gridDelegate:
                        const SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 3, //横轴三个子widget
                      childAspectRatio: 1, //宽高比为1时，子widget
                    ),
                    children: const [
                      Icon(Icons.ac_unit),
                      Icon(Icons.airport_shuttle),
                      Icon(Icons.all_inclusive),
                      Icon(Icons.beach_access),
                      Icon(Icons.cake),
                      Icon(Icons.free_breakfast)
                    ],
                  ),
                );
              }),
            );
          },
          child: const ListTile(
            title: Text('GridView'),
          ),
        ),
        GestureDetector(
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (_) {
                final data = [
                  const Icon(Icons.ac_unit),
                  const Icon(Icons.airport_shuttle),
                  const Icon(Icons.all_inclusive),
                  const Icon(Icons.beach_access),
                  const Icon(Icons.cake),
                ];
                return CommonPage(
                  title: 'GridView.builder',
                  body: GridView.builder(
                    gridDelegate:
                        const SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 3, //横轴三个子widget
                      childAspectRatio: 1.5, //宽高比为1时，子widget
                    ),
                    itemCount: data.length,
                    itemBuilder: (context, index) {
                      return data[index];
                    },
                  ),
                );
              }),
            );
          },
          child: const ListTile(
            title: Text('GridView.builder'),
          ),
        ),
        GestureDetector(
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (_) {
                return CommonPage(
                  title: 'PageView',
                  body: PageView(
                    children: const [
                      Center(child: Text("1", textScaleFactor: 5)),
                      Center(child: Text("2", textScaleFactor: 5)),
                      Center(child: Text("3", textScaleFactor: 5)),
                    ],
                  ),
                );
              }),
            );
          },
          child: const ListTile(
            title: Text('PageView'),
          ),
        ),
        GestureDetector(
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (_) {
                final data = '12345'.split('');
                return CommonPage(
                  title: 'PageView.builder',
                  body: PageView.builder(
                    itemCount: data.length,
                    itemBuilder: (context, index) {
                      return KeepAliveWrapper(
                        child: TestPageView(page: index + 1),
                      );
                    },
                  ),
                );
              }),
            );
          },
          child: const ListTile(
            title: Text('PageView.builder'),
          ),
        ),
        GestureDetector(
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (_) {
                List tabs = ["新闻", "历史", "图片"];
                return DefaultTabController(
                  length: tabs.length,
                  child: CommonPage(
                    title: 'TabBarView',
                    appBarBottom: TabBar(
                      tabs: tabs.map((e) => Tab(text: e)).toList(),
                    ),
                    body: TabBarView(
                      children: tabs.map((e) {
                        return KeepAliveWrapper(
                          child: Center(
                            child: Text(e, textScaleFactor: 5),
                          ),
                        );
                      }).toList(),
                    ),
                  ),
                );
              }),
            );
          },
          child: const ListTile(
            title: Text('TabBarView'),
          ),
        ),
        GestureDetector(
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (_) {
                return CustomScrollView(
                  slivers: [
                    const SliverAppBar(
                      pinned: true, // 滑动到顶端时会固定住
                      expandedHeight: 250, // 展开时的高度
                      // collapsedHeight: 100, // 收缩起来的高度
                      flexibleSpace: FlexibleSpaceBar(
                        title: Text('CustomScrollView'),
                        background: Image(
                          image: NetworkImage(
                              "https://avatars2.githubusercontent.com/u/20411649?s=460&v=4"),
                          fit: BoxFit.cover,
                        ),
                      ),
                    ),
                    SliverPadding(
                      padding: const EdgeInsets.all(8.0),
                      sliver: SliverGrid(
                        //Grid
                        gridDelegate:
                            const SliverGridDelegateWithFixedCrossAxisCount(
                          crossAxisCount: 2,
                          mainAxisSpacing: 10.0,
                          crossAxisSpacing: 10.0,
                          childAspectRatio: 4.0,
                        ),
                        delegate: SliverChildBuilderDelegate(
                          (BuildContext context, int index) {
                            //创建子widget
                            return Container(
                              alignment: Alignment.center,
                              color: Colors.cyan[100 * (index % 9)],
                              child: Text('grid item $index'),
                            );
                          },
                          childCount: 20,
                        ),
                      ),
                    ),
                    SliverFixedExtentList(
                      itemExtent: 50.0,
                      delegate: SliverChildBuilderDelegate(
                        (BuildContext context, int index) {
                          //创建列表项
                          return Container(
                            alignment: Alignment.center,
                            color: Colors.lightBlue[100 * (index % 9)],
                            child: Text('list item $index'),
                          );
                        },
                        childCount: 20,
                      ),
                    ),
                  ],
                );
              }),
            );
          },
          child: const ListTile(
            title: Text('CustomScrollView'),
          ),
        ),
        GestureDetector(
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (_) {
                return NestedScrollView(
                  headerSliverBuilder:
                      (BuildContext context, bool innerBoxIsScrolled) {
                    return [
                      SliverAppBar(
                        title: innerBoxIsScrolled
                            ? const Text('NestedScrollView')
                            : null,
                        expandedHeight: 200,
                        pinned: true,
                        flexibleSpace: FlexibleSpaceBar(
                          background: Image.network(
                            'https://upload.jianshu.io/users/upload_avatars/24645157/484d7659-daeb-455c-9e08-28d0a057c9be.jpg?imageMogr2/auto-orient/strip%7CimageView2/1/w/100/h/100',
                            fit: BoxFit.cover,
                          ),
                          collapseMode: CollapseMode.parallax,
                        ),
                      ),
                    ];
                  },
                  body: ListView.builder(
                    padding: EdgeInsets.zero,
                    itemBuilder: (BuildContext context, int index) {
                      return ListTile(
                        title: Text('List $index'),
                      );
                    },
                    itemCount: 20,
                  ),
                );
              }),
            );
          },
          child: const ListTile(
            title: Text('NestedScrollView'),
          ),
        ),
      ],
    );
  }
}
